package com.example.reward.intercept;// SecureInterceptor.java

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class SecureInterceptor implements Interceptor {

    private final String appId;
    private final String secret;

    public SecureInterceptor(String appId, String secret) {
        this.appId = appId;
        this.secret = secret;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        long timestamp = System.currentTimeMillis();
        String signature;
        try {
            signature = hmacSHA256(appId + timestamp, secret);
        } catch (Exception e) {
            throw new IOException("签名生成失败", e);
        }

        Request newRequest = chain.request().newBuilder()
                .addHeader("X-App-Id", appId)
                .addHeader("X-Timestamp", String.valueOf(timestamp))
                .addHeader("X-Signature", signature)
                .build();

        return chain.proceed(newRequest);
    }

    private String hmacSHA256(String data, String secret) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256_HMAC.init(secretKey);
        byte[] hash = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(hash); // Base64 返回可读字符串
    }
}
